// 源插件
import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { DateDiff, FormatnumberZero, Mover, NumberDivide } from '@/function.js';
// 视图插件
import { Button, Form, Icon, Input } from 'antd';
// 外部组件
import StandardTable from '@/components/StandardTable';
import Loading from '@/components/Loading/Loading';

// css OR less预编译器
import styles from './PositionRuiOptionsTable.less';

// 图片

// 算式

/* 切割日期 */
function StringSplit(date) {
  // 日期
  if (typeof date === 'string') {
    return date.split(' ')[0];
  }
  return null;
}

/* 财报日剩余对比 */
function DateDiffResults(sDate2) {
  // sDate1和sDate2是yyyy-MM-dd格式
  if (typeof sDate2 === 'string') {
    let aDate;
    let oDate1;
    let oDate2;
    let iDays;
    oDate1 = new Date(); // 转换为yyyy-MM-dd格式
    aDate = sDate2.split('/');
    oDate2 = new Date(`${aDate[1]}-${aDate[2]}-${aDate[0]}`);
    iDays = parseInt(Math.abs(oDate1 - oDate2) / 900 / 60 / 60 / 24); // 把相差的毫秒数转换为天数
    return iDays; // 返回相差天数
  }
  return '暂无数据';
}
function DateStamp(param) {
  // sDate1和sDate2是yyyy-MM-dd格式
  const str = param.replace(/-/g, '/');
  const date = new Date(str);
  date.setDate(date.getDate() + 1);
  return date;
}

/**
 *  Created by xjc on 2019/5/15
 *  Describe:数据连接
 */

@connect(({ positionrui, loading }) => ({
  positionrui,
  loading: loading.models.positionruiRule,
}))
@Form.create()
class PositionRuiOptionsModalTable extends PureComponent {
  componentWillMount() {}

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:当前状态
   */

  state = {
    listLoading: false, // 加载状态
    selectedRows: [], // 选择行
    formValues: {
      num: 10,
      page: 1,
    }, // 表格参数
    record: {}, // 当前行内容
    searchText: '', // 搜索内容
    columns: [], // 表头处理结果
  };
  /**
   *  Describe:本地搜索
   *  Created by xjc on 2019/6/4
   */

  getColumnSearchProps = dataIndex => ({
    filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
      <div style={{ padding: 8 }}>
        <Input
          ref={node => {
            this.searchInput = node;
          }}
          placeholder={`Search ${dataIndex}`}
          value={selectedKeys[0]}
          onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
          onPressEnter={() => this.handleSearch(selectedKeys, confirm)}
          style={{ width: 188, marginBottom: 8, display: 'block' }}
        />
        <Button
          type="primary"
          onClick={() => this.handleSearch(selectedKeys, confirm)}
          icon="search"
          size="small"
          style={{ width: 80, marginRight: 8 }}
        >
          搜索
        </Button>
        <Button onClick={() => this.handleReset(clearFilters)} size="small" style={{ width: 80 }}>
          重置
        </Button>
      </div>
    ),
    filterIcon: filtered => (
      <Icon type="search" style={{ color: filtered ? '#1880ff' : '#181816', fontWeight: '700' }} />
    ),
    onFilter: (value, record) => {
      return record[dataIndex] === null
        ? ''
        : record[dataIndex]
            .toString()
            .toLowerCase()
            .includes(value.toLowerCase());
    },
    onFilterDropdownVisibleChange: visible => {
      if (visible) {
        setTimeout(() => this.searchInput.select());
      }
    },
    render: text => <span>{text}</span>,
  });

  handleSearch = (selectedKeys, confirm) => {
    confirm();
    this.setState({ searchText: selectedKeys[0] });
  };

  handleReset = clearFilters => {
    clearFilters();
    this.setState({ searchText: '' });
  };

  getColumns() {
    const {
      positionrui: { optionsFilters },
    } = this.props;
    return [
      /*    {
            title: '序号',
            dataIndex: 'p',
          }, */
      {
        title: '股票代码',
        ...this.getColumnSearchProps('name'),
        dataIndex: 'name',
        sorter: (a, b) => {
          const c = [a.name, b.name].sort();
          if (c[0] === a.name) {
            return 1;
          }
          return -1;
        },
      },
      {
        title: '类型',
        dataIndex: 'typename',
        filters: [
          {
            text: 'Sell Put',
            value: 'Sell Put',
          },
          {
            text: 'Sell Call',
            value: 'Sell Call',
          },
        ],
        onFilter: (value, record) => {
          if (record.typename != undefined) {
            return record.typename.indexOf(value) === 0;
          }
        },
        render: tags => {
          return <span>{tags == 'Sell Call' ? 'SC' : tags == 'Sell Put' ? 'SP' : ''}</span>;
        },
      },
      {
        title: '执行价',
        dataIndex: 'strikeprice',
        sorter: (a, b) => a.strikeprice - b.strikeprice,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '当前价',
        dataIndex: 'closeprice',
        sorter: (a, b) => a.closeprice - b.closeprice,
        render: text => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide((Math.floor(text * 100) / 100).toString())
                : null}
            </span>
          );
        },
      },

      {
        title: '距执行幅度',
        dataIndex: 'pricerate',
        sorter: (a, b) => a.pricerate - b.pricerate,
        render: text => {
          let priceratetext = '';
          if (text > 0) {
            priceratetext = `${text}%`;
          }
          return <span>{priceratetext}</span>;
        },
      },
      {
        title: '成本价',
        dataIndex: 'costprice',
        sorter: (a, b) => a.costprice - b.costprice,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },

      {
        title: '现价',
        dataIndex: 'newprice',
        sorter: (a, b) => a.newprice - b.newprice,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '剩余期权比',
        dataIndex: 'premiumrate',
        render: text => {
          let premiumratetext = '';
          if (text > 0) {
            premiumratetext = `${text}%`;
          }
          return <span>{premiumratetext}</span>;
        },
        sorter: true,
      },

      {
        title: '股数',
        dataIndex: 'stocknumber',
        sorter: (a, b) => a.stocknumber - b.stocknumber,
        render: (value, row, index) => {
          return (
            <span>
              {typeof value === 'number' || typeof value === 'string'
                ? NumberDivide(value.toString())
                : null}
            </span>
          );
        },
      },
      {
        title: '当日盈亏',
        dataIndex: 'thisincome',
        sorter: true,
        render: (tags, record) => {
          const bili = record.thisincome / (record.stocknumber * record.costprice);
          let color = '';
          if (bili < -0.4) {
            color = '#be5eed';
          } else if (bili > -0.4 && bili < -0.2) {
            color = '#9218cd';
          } else if (bili > -0.2 && bili < 0) {
            color = '#601386';
          } else if (bili == 0) {
            color = '#201a23';
          } else if (bili > 0 && bili < 0.2) {
            color = '#f86d75';
          } else if (bili > 0.2 && bili < 0.4) {
            color = '#f3353f';
          } else if (bili > 0.2) {
            color = '#c70f19';
          } else {
            color = '#8a0a11';
          }
          return <span style={{ color }}>{tags}</span>;
        },
      },
      {
        title: '盈亏金额',
        dataIndex: 'allincome',
        sorter: (a, b) => a.allincome - b.allincome,
      },
      {
        title: '初始期权金',
        dataIndex: 'allpremium',
        sorter: (a, b) => a.allpremium - b.allpremium,
      },
      {
        title: '剩余期权金',
        dataIndex: 'remainpremium',
        sorter: (a, b) => a.remainpremium - b.remainpremium,
      },

      {
        title: '操作时间',
        dataIndex: 'tradedate',
        sorter: true,
      },
      {
        title: '到期时间',
        dataIndex: 'expiry',
        sorter: true,
      },
      {
        title: '剩余天数',
        dataIndex: 'remaindays',
        sorter: (a, b) => a.remaindays - b.remaindays,
      },
      {
        title: '头寸规模',
        dataIndex: 'sumprice',
        sorter: (a, b) => a.sumprice - b.sumprice,
        fixed: 'right',
      },
    ];
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    /* 导入列表数据 */
    dispatch({
      type: 'positionrui/ChangeOptionsPage',
      payload: {
        num: pagination.pageSize,
        page: pagination.current,
        total: pagination.total,
      },
      callback: res => {},
    });
  };

  /**
   *  Created by xjc on 2019/5/15
   *  Describe:视图
   */

  render() {
    const {
      loading,
      positionrui: { optionsmodal },
      OptionVisible,
    } = this.props;
    const { listLoading, selectedRows, record, OptionsDetailVisible } = this.state;
    let columns = [];
    const optionsList = [];
    if (columns.length === 0 && optionsmodal.code === 1) {
      columns = this.getColumns();
    }
    return (
      <div>
        {optionsmodal.list.length === 0 ? (
          <Loading />
        ) : (
          <StandardTable
            scroll={{ x: 'auto' }}
            selectedRows={selectedRows}
            loading={listLoading}
            data={optionsmodal}
            columns={columns}
            style={{ tableLayout: 'fixed' }}
            className={styles.TableLayout}
            onChange={this.handleStandardTableChange}
          />
        )}
      </div>
    );
  }

  componentDidMount() {
    const { dispatch, stock } = this.props;
    /* 导入列表数据 */
    dispatch({
      type: 'positionrui/GetFssFundOptionsList',
      payload: stock,
    });
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    /* 导入列表数据 */
    dispatch({
      type: 'positionrui/GetFssFundOptionsListClear',
      callback: res => {},
    });
  }
}

export default PositionRuiOptionsModalTable;
